package com.plant.address.service.impl;

import com.plant.address.domain.MyAddress;
import com.plant.address.feign.UserFeign;
import com.plant.address.mapper.MyAddressMapper;
import com.plant.address.service.MyAddressService;
import com.plant.common.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class MyAddressServiceImpl implements MyAddressService {

    @Autowired
    private MyAddressMapper myAddressMapper;

    @Autowired
    private UserFeign userFeign;

    @Override
    public List<MyAddress> findAllAddress(MyAddress myAddress) {
        return myAddressMapper.findAllAddress(myAddress);
    }
    @Transactional
    @Override
    public int myAddressAdd(MyAddress myAddress) {
        log.info("myAddress:{}", myAddress);
        // 检查当前地址是否设置为默认地址
        if (myAddress.getIsDefault()!= null && myAddress.getIsDefault()==true) {
            myAddressMapper.update1(myAddress.getUserId());
            myAddressMapper.myAddressAdd(myAddress);
        }else {
            myAddress.setIsDefault(false);
            int i = myAddressMapper.myAddressAdd(myAddress);
            // 返回新增地址的结果
            return i;
        }
        return 1;
    }

    @Override
    public List<MyAddress> findById(Integer userId) {
        return myAddressMapper.findById(userId);
    }

    @Override
    public int delete(Integer id) {
        return myAddressMapper.delete(id);
    }

    @Override
    public int update(MyAddress myAddress) {
        if(myAddress.getIsDefault()!=null && myAddress.getIsDefault()==true){
            myAddressMapper.update1(myAddress.getUserId());
            myAddressMapper.update(myAddress);
        }else {
            return myAddressMapper.update(myAddress);
        }
        return 1;
    }

    @Override
    public MyAddress findByAddId(Integer id) {
        return myAddressMapper.findByAddId(id);
    }
}
